import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';

class EditPassword extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text('修改密码'),
        centerTitle: true,
        elevation: 0.0,
      ),
      body: Theme(
        data: Theme.of(context).copyWith(
          primaryColor: Colors.black,
        ),
        child: Container(
          padding: EdgeInsets.all(16.0),
          child: KeyboardAvoider(
              autoScroll: true,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  EditPasswordForm(),
                ],
              )),
        ),
      ),
    );
  }
}

class EditPasswordForm extends StatefulWidget {
  @override
  EditPasswordFormState createState() => EditPasswordFormState();
}

class EditPasswordFormState extends State<EditPasswordForm> {
  final editPasswordFormKey = GlobalKey<FormState>();
  String oldPassword, newPassword;
  bool autovalidate = false;
  String uniqueId = '';
  void submitEditPasswordForm() {
    if (editPasswordFormKey.currentState.validate()) {
      editPasswordFormKey.currentState.save();
      this.fetchPosts(oldPassword, newPassword);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  String validateOldPassword(value) {
    if (value.isEmpty) {
      return '请输入当前密码！';
    }
    return null;
  }

  String validateNewPassword(value) {
    if (value.isEmpty) {
      return '请输入新密码！';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: editPasswordFormKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: '当前密码',
              helperText: '',
            ),
            onSaved: (value) {
              oldPassword = value;
            },
            validator: validateOldPassword,
            // autovalidate: autovalidate,
          ),
          TextFormField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: '新密码',
              helperText: '',
            ),
            onSaved: (value) {
              newPassword = value;
            },
            validator: validateNewPassword,
            // autovalidate: autovalidate,
          ),
          SizedBox(
            height: 32.0,
          ),
          Container(
            width: double.infinity,
            child: ElevatedButton(
              // color: Theme.of(context).accentColor,
              child: Text('确认', style: TextStyle(color: Colors.white)),
              onPressed: submitEditPasswordForm,
            ),
          ),
        ],
      ),
    );
  }

  Future fetchPosts($oldPassword, $newPassword) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dataBody =
        jsonEncode({'oldPassword': $oldPassword, 'newPassword': $newPassword});
    final response = await http.post(
        'https://me.yuanqiao.pw/api/me/edit-password.php',
        body: dataBody,
        headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')});
    EasyLoading.dismiss();
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      var state = responseBody['state'];
      if (state == '1') {
        String token = responseBody['data'];
        SharedPreferences prefs = await SharedPreferences.getInstance();
        final setTokenResult = await prefs.setString('user_token', token);
        if (setTokenResult) {
          Fluttertoast.showToast(
              msg: responseBody['error'],
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.white,
              textColor: Colors.black87,
              fontSize: 16.0);
          Navigator.pop(context);
        } else {
          Fluttertoast.showToast(
              msg: responseBody['error'],
              toastLength: Toast.LENGTH_SHORT,
              gravity: ToastGravity.CENTER,
              timeInSecForIosWeb: 1,
              backgroundColor: Colors.white,
              textColor: Colors.black87,
              fontSize: 16.0);
        }
      } else {
        Fluttertoast.showToast(
            msg: responseBody['error'],
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.white,
            textColor: Colors.black87,
            fontSize: 16.0);
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
